<?php

//为解决合并问题，先暂时把功能把到这个文件中，将来再合并过来
require_once APPLICATION_PATH . '/modules/default/controllers/MemberExtController.php';

/*
 * 会员中心
 */
class MemberController extends MemberExtController {

    public function init() {

        parent::init();
        //$this->_helper->redirector('login','user');
        //加载公共js
        $this->appendScript('/js/jquery.min.js')->appendScript('/js/jquery.validate.min.js')->appendScript('/js/messages_cn.js')->appendScript('/js/uuch.js');
        $this->view->menuId = $this->getRequest()->getParam('action');
        $userid = $this->currentUser()->Id;

        $uCount = array();
        Application_Model_StoreItem::getInTypeCount(1, -1);

        //获取用户仓库总数
        $utemp = Application_Model_StoreItem::getItemCount($userid, -1);
        if ($utemp == null) {
            $utemp = 0;
        }
        $uCount["store"] = $utemp;

        //入报入库
        $utemp = Application_Model_ingstore::getItemCount($userid, 0);
        if ($utemp == null) {
            $utemp = 0;
        }
        $uCount["ingstore"] = $utemp;

        //运单总数
        $utemp = Application_Model_wayBillItem::getItemCount($userid, -1);
        if ($utemp == null) {
            $utemp = 0;
        }
        $uCount["will"] = $utemp;


        $this->view->user = $this->currentUser();

        //订单总数
        $uCount["order"] = Application_Model_Order::getUncomplate($userid);
        $uCount['mail'] = $this->view->mainCount;


        //优惠券
        $utemp = Application_Model_Coupon::getItemCount($userid, -1);
        if ($utemp == null) {
            $utemp = 0;
        }

        $uCount["Coupon"] = $utemp;

        $this->view->uCount = $uCount;
    }

    public function storeaddressAction() {
        
    }

    /*
     * 我的仓库主页
     */

    public function storehomeAction() {
        $this->setTitle('我的云仓库 | 集中管理，集中配送，更能节省运费');
        $this->appendScript('/js/jquery.min.js')->appendScript('/js/clip/zeroclipboard.js');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css'); //   

        $this->view->storeAddress = Application_Model_Config::getStoreAddress()->Value;
        //购物车信息
        $this->view->cart = Application_Model_Cart::current();
    }

    //预报入库
    /*
     * 预报入库
     */
    public function instoreAction() {
        $this->setTitle('预报入库 | 无需代购，自主买遍国货');
        $this->appendCss('/css/home/warehouse.css'); //    
        //$this->appendCss('/css/express.css');
        $request = $this->getRequest();
        
        $words = array();
        for ($i = 0; $i < 26; $i++) {
            $words [] = chr(65 + $i);
        }
        $this->view->words = $words;
        
        $expressid = $this->_getParam('expressid');
        $this->view->expressno = $this->_getParam('expressno');
        $this->view->name = $this->_getParam('name');

        $express = Application_Model_shipType::load($expressid);
        if ($express != NULL) {
            $this->view->expressname = $express->Name;
            $this->view->expressid = $express->Id;
        } else {
            $this->view->expressname = '申通';
            $this->view->expressid = '9';
        }

        if ($request->isPost()) {
            //提交
            $userid = $this->currentUser()->Id;

            $urls = $this->_getParam("url");

            //$shipTypes= explode(",",$this->_getParam("shipType"));

            $newItem = new Application_Model_ingstore();
            $newItem->name = $this->_getParam("name");
            $newItem->type = $this->_getParam("hasDetail");
            $newItem->shipTypeid = $this->_getParam('expressid'); //?
            $newItem->shipType = $this->_getParam('expressname');
            $newItem->shipNo = $this->_getParam("logistics");
            $newItem->url = '';  //商品信息
            $newItem->remark = $this->_getParam("remark");
            $newItem->createtime = date('Y-m-d H:i:s');
            //$newItem->intime=$this->_getParam("intype");
            $newItem->state = 0;
            $newItem->userid = $userid;
            $newItem->save();

            $num = 0;

            /*
              foreach ($urls as $urlItem) {
              if($urlItem && $urlItem!=''){
              $addItem=new Application_Model_ingstoreproduct();
              $addItem->ingstoreid=$newItem->id;
              $addItem->url=$urlItem;
              $addItem->image='';
              $addItem->state=0;
              $addItem->save();
              $num++;
              }
              }
             * 
             */

            $event = new Application_Model_event();
            $event->userid = $userid;
            $event->username = $this->currentUser()->nikename;
            $event->opType = '预报入库';
            $event->opTime = date('Y-m-d H:i:s');
            $event->opCaption = '预报一个包裹：来源【' . $this->_getParam("intype") . '】';
            $event->url = '';
            $event->save();

            $this->view->newItem = $newItem;
            $this->view->addFlag = 1;
            $this->view->num = $num;
        } else {
            $this->view->storeAddress = Application_Model_Config::getStoreAddress()->Value; //仓库地址 
            $shipTypes = Application_Model_shipType::getbyType(1); //获取快递公司列表
            $this->view->shipTypes = $shipTypes;
        }
    }

    //我的仓库
    /**
     *  我的仓库
     */
    public function mystoreAction() {
        $this->setTitle('我的仓库 | 您的金牌仓库管家');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css');
        $this->appendScript('/js/jquery.min.js');

        $start = $this->_getParam('start');
        if (!$start) {
            $start = 0;
        }

        $userid = $this->currentUser()->Id;
        $this->view->stores = Application_Model_StoreItem::getMyStore($userid, $this->pageSize, $start);
        $selected = Application_Model_StoreItem::getMySelect($userid);

        $this->view->selected = array('count' => count($selected), 'weight' => Application_Model_StoreItem::getSumWeight($selected));
        $this->view->storelist = $this->view->stores['list'];
    }

    /**
     * 仓库历史
     */
    public function storehistoryAction() {
        $this->setTitle('仓库历史记录');
        $this->appendCss('/css/Share.css')->appendCss('/css/home/warehouse.css')->appendScript('/js/jquery.min.js');

        $start = $this->_getParam('start');
        if (!$start) {
            $start = 0;
        }

        $stime = $this->_getParam('stime');
        if (!$stime)
            $stime = -3;

        $etime = $this->_getParam('etime');
        if (!$etime)
            $etime = 1;

        $this->pageSize = 10;
        $userid = $this->currentUser()->Id;
        $this->view->stores = Application_Model_StoreItem::getByFilter(NULL, $userid, NULL, NULL, Application_Model_StoreItem::STATUS_Sended, $this->pageSize, $start);

        $this->view->storelist = $this->view->stores['list'];
    }

    public function forecastlistAction() {
        $this->setTitle('我的仓库 | 预报列表 | 您的金牌仓库管家');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/warehouse.css'); //            
        $this->appendScript('/js/jquery.min.js');

        $oper = $this->_getParam('oper');
        if ($oper == "del") {
            $id = $this->_getParam("id");
            Application_Model_ingstore::cancel($id);
        }

        $start = $this->_getParam('start');
        if (!$start)
            $start = 0;

        $state = $this->_getParam('state');
        if (!$state)
            $state = 0;

        $stime = $this->_getParam('stime');
        if (!$stime)
            $stime = -3;

        $etime = $this->_getParam('etime');
        if (!$etime)
            $etime = 1;

        $this->pageSize = 10;

        $userid = $this->currentUser()->Id;
        $this->view->ingstores = Application_Model_ingstore::getByFilter(NULL, $userid, date('Y-m-d', strtotime("$stime months")), date('Y-m-d', strtotime("$etime months")), $state, $this->pageSize, $start);


        $this->view->ingstorelist = $this->view->ingstores['list'];
    }

    /**
     * 运单管理
     */
    public function waybillAction() {
        $this->setTitle('运单管理 |  集中管理，集中配送，更能节省运费');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/home/waybill.css'); // 

        $oper = $this->_getParam("oper");
        if ($oper == "cancel") {
            //撤消运单
            $id = $this->_getParam("id");
            $way = Application_Model_wayBillItem::load($id);
            if ($way->UserId != $this->currentUser()->Id) {
                $this->redirect('waybill', 'member');
                return;
            }

            $way->cancelWay();
            //Application_Model_wayBillItem::cancel($id);
            //撤消仓库单
            //Application_Model_StoreItem::cancelForWay($id);
        } else if ($oper == "sign") {
            //确认收货
            $id = $this->_getParam("id");
            Application_Model_wayBillItem::sign($id);
        }

        $start = $this->_getParam('start');
        if (!$start) {
            $start = 0;
        }

        $this->pageSize = 10;

        $userid = $this->currentUser()->Id;
        $this->view->waybills = Application_Model_wayBillItem::getByFilter(NULL, $userid, date('Y-m-d', strtotime('-10 months')), date('Y-m-d', strtotime('+10 days')), null, $this->pageSize, $start);

        $this->view->waybilllist = $this->view->waybills['list'];
    }

    /**
     * 验证优惠券
     */
    public function validatecouponAction() {
        $no = $this->_getParam('couponno');
        $money = $this->_getParam('money');
        $userid = $this->currentUser()->Id;
        $password = $this->_getParam('password');

        $coupon = Application_Model_Coupon::getByNo($no);
        $result = $coupon->Validate($userid, $money, $password);
        $this->json($result);
    }

    public function waybillshow() {
        $ids = $this->_getParam('ids');
        $this->view->ids = $ids;
        $Stores = Application_Model_StoreItem::getByids($ids);
        $userid = $this->currentUser()->Id;
        if (empty($Stores)) {
            //跳转到运单列表页
            $this->_redirector = $this->_helper->getHelper('Redirector');
            $this->_redirector->gotoUrl('/member/mystore');
            return;
        }

        //$productCount = 0; 
        $weightCount = 0;
        //$timeOutCount = 0;

        $volumWeight = 0;

        foreach ($Stores as $item) {
            if ($item->WayId) {
                $this->redirect('mystore', 'member');
                return;
            }

            $weightCount+=$item->weight; //计算总重量

            if ($item->VolumeWeight) {
                $volumWeight += $item->VolumeWeight;
            } else {
                $volumWeight += $item->Weight;
            }
        }
        $packWeight = Uuch_Util::getPackage($weightCount);

        $storeCount = count($Stores);

        $this->view->adds = Application_Model_address::getbyuid($userid);
        //获取默认邮寄地址
        $cityId = 1;
        if (count($this->view->adds) == 0) {
            $address = new Application_Model_address();
            $this->view->defaultAddress = $address;
        } else {
            $this->view->defaultAddress = $this->view->adds[0];
            $cityId = $this->view->defaultAddress->State;
        }

        $prices = Application_Model_Express::getPricesByCity($cityId);
        $this->view->prices = $prices;

        //获取配送方式
        //$shipFeeConfigitems = Application_Model_shipFeeConfig::getbyCityid(1);
        //页面需要展示内容       
        $this->view->Stores = $Stores;
        $this->view->storeCount = $storeCount; //库存数
        $this->view->weightCount = $weightCount; //总重量
        $this->view->packWeight = $packWeight; //包裹重量

        $this->view->volumeWeight = $volumWeight;
        //
        //$this->view->productCount = $productCount; //商品总数
        //$this->view->timeOutCount = $timeOutCount; //超时费用                    
        //$this->view->shipFeeConfigitems = $shipFeeConfigitems; //配送方式
        //自发包裹数量 
        //购物包裹数量
        //收货信息


        $words = array();
        for ($i = 0; $i < 26; $i++) {
            $words [] = chr(65 + $i);
        }
        $this->view->words = $words;

        $this->view->coupons = Application_Model_Coupon::getByUser($userid, Application_Model_Coupon::STATUS_OK);
    }

    public function waybillinfoAction() {
        $this->setTitle('运单管理 |  集中管理，集中配送，更能节省运费');

        $this->appendCss('/css/Share.css'); //            

        $this->appendCss('/css/home/waybill.css'); // 

        $id = $this->_getParam('id');
        //获取运单信息
        if ($id) {
            $waybill = Application_Model_wayBillItem::load($id);
            if ($waybill->UserId != $this->currentUser()->Id) {
                $this->redirect('waybill', 'member');
                return;
            }
            
            $this->view->waybill = $waybill;
        }
    }

    /*
     * 运单评论
     */

    public function evaluateAction() {
        $this->setTitle('运单管理 |  集中管理，集中配送，更能节省运费');
        $this->appendCss('/css/Share.css'); //    
        $this->appendCss('/css/evaluate.css'); // 
        $this->appendCss('/css/warehouse.css'); // 

        $id = $this->_getParam('id');
        if (!$id) {
            $this->_redirector = $this->_helper->getHelper('Redirector');
            $this->_redirector->gotoUrl('/member/waybill');
            exit;
        }

        $wayItem = new Application_Model_wayBillItem($id);
        if (!$wayItem || $wayItem->status != 100) {
            $this->_redirector = $this->_helper->getHelper('Redirector');
            $this->_redirector->gotoUrl('/member/waybill');
            exit;
        }
        $request = $this->getRequest();
        if ($request->isPost()) {
            $userid = $this->currentUser()->Id;

            $newItem = new Application_Model_comment();
            $newItem->userid = $this->currentUser()->Id;
            $newItem->username = $this->currentUser()->username;
            $newItem->area = ''; //区域
            $newItem->type = 0;
            $newItem->code = $wayItem->id;
            $newItem->logistics = $this->_getParam("logistics");
            $newItem->service = $this->_getParam("service");
            $newItem->comment = $this->_getParam("comment");
            $newItem->createtime = date('Y-m-d H:i:s');
            $newItem->parentid = 0;
            $newItem->points = 10;
            $newItem->save();
            //更新运单信息
            $wayItem->comment = $newItem->id;
            $wayItem->save();

            $this->_redirector = $this->_helper->getHelper('Redirector');
            $this->_redirector->gotoUrl('/member/waybill');
            exit;
        }


        $this->view->wayItem = $wayItem;
    }

    /**
     * 提现
     */
    public function withdrawAction() {
        $this->setTitle('我的帐户 |  提现');
        $start = $this->_getParam('start');
        if (!$start) {
            $start = 0;
        }
        $this->pageSize = 10;

        $this->appendCss('/css/home/rmb.css');
        $this->view->account = $this->currentUser()->Account;
        $this->view->history = $this->view->account->getMoneyChange(date('Y-m-d', strtotime('-1 years')), date('Y-m-d', strtotime('+1 days')), $this->pageSize, $start);
        $this->view->historyList = $this->view->history['list'];

        $request = $this->getRequest();
        if ($request->isPost()) {
            $ret = array(
                "ret" => 0,
                "msg" => ''
            );

            $withDrawMoney = $request->getParam('submit_withdraw');
            $state = $request->getParam('state');
            $logid = $request->getParam('logid');

            //写入UUCH_Cash
            $cash = new Application_Model_cash();
            $cash->Money = $withDrawMoney;
            $cash->CashTime = date('Y-m-d H:i:s', time());
            $cash->State = 0;
            $cash->Uid = $this->currentUser()->Account->Id;
            $cash->Logid = $logid;
            $cash->Remark = ($state == "5") ? "撤消" : "提现";
            $cash->save();

            //将充值记录表中状态置为2.   保存对象是否正确？
            $item = new Application_Model_UserAccountHistory($logid);
            $item->State = 5;
            $item->save();

            $ret['ret'] = 1;

            echo json_encode($ret);
            exit;
        }
    }

    public function canelwithdrawAction() {
        $this->setTitle('我的帐户 |  提现');
        $request = $this->getRequest();
        if ($request->isPost()) {
            $ret = array(
                "ret" => 0,
                "msg" => ''
            );

            $id = $request->getParam('id');

            //修改UUCH_Cash，根据状态(0)，logid获取 cash 对象
            $cash = Application_Model_cash::getByLogidAndState($id, 0);
            if ($cash) {
                $cash->State = -1;
                $cash->save();

                $logid = $cash->Logid;

                //将充值记录表中状态置为2.   保存对象是否正确？
                $item = new Application_Model_UserAccountHistory($logid);
                $item->State = 1;
                $item->save();

                $ret['ret'] = 1;
            }

            echo json_encode($ret);
            exit;
        }
    }

    /*
     * 退款列表
     */

    public function withdrawlistAction() {
        $this->setTitle('我的帐户 |  提现列表');
        $this->appendCss('/css/home/rmb.css');
        $this->view->account = $this->currentUser()->Account;
        $this->view->history = $this->view->account->getMoneyChange(date('Y-m-d', strtotime('-1 years')), date('Y-m-d', strtotime('+1 days')));
    }

    /*
     * 优惠券功能
     */

    public function couponAction() {
        $this->setTitle('我的帐户 |  优惠券功能');
        $this->appendCss('/css/home/coupon.css');


        $start = $this->_getParam('start');
        if (!$start)
            $start = 0;

        $status = $this->_getParam('status');
        if (!$status)
            $status = 1;

        $stime = $this->_getParam('stime');
        if (!$stime)
            $stime = -3;

        $etime = $this->_getParam('etime');
        if (!$etime)
            $etime = 1;

        $this->pageSize = 10;

        $userid = $this->currentUser()->Id;
        $this->view->coupons = Application_Model_Coupon::getByFilter(NULL, $userid, date('Y-m-d', strtotime("$stime months")), date('Y-m-d', strtotime("$etime months")), $status, $this->pageSize, $start);

        $this->view->payStatus = Application_Model_Coupon::getCountByStatus($this->currentUser()->Id, 1);
        $this->view->timesStatus = Application_Model_Coupon::getCountByStatus($this->currentUser()->Id, 1, date("Y-m-d H:i:s", 1344413288), date('Y-m-d', strtotime('+3 months')));

        $this->view->coupon = $this->view->coupons['list'];
        $this->view->status = $status;
    }

    public function pointAction() {
        $this->appendCss('/css/home/point.css');
    }

    public function refundAction() {
        $this->appendCss('/css/home/rmb.css');
    }

    /**
     * 支付宝充值码
     */
    public function alipaycodeAction() {
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/alipaycode.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $this->setTitle('购买充值码');

        //暂时一致
        $request = $this->getRequest();
        if ($request->isPost()) {
            $currentUser = $this->currentUser();
            $currentUserAccount = $currentUser->Account;
            $user_money = $currentUserAccount->Money;

            $money = $request->getParam('money');
            $typeId = $request->getParam('type');
            //先判断卡是否
            $card = Application_Model_PayCodeCard::getFirstByType($typeId, 0);

            if ($card != null) {//库存足够
                //1获取卡信息
                $card->userID = $currentUser->Id;
                $card->state = 5;
                $card->userTime = date("Y-m-d H:i:s", time());
                $card->save();
                //2新增订单记录
                $addOrder = new Application_Model_PayCodeOrder();
                $addOrder->uid = $currentUser->Id; //用户ID	
                $addOrder->userName = $currentUser->nikename; //用户名	
                $addOrder->money = $money; //金额        
                $addOrder->cardid = $card->id; //授权卡序号	
                $addOrder->cardno = $card->cardNo; //授权卡号   	
                $addOrder->verifyCode = $card->cardPwd; //授权密码
                $addOrder->typeid = $card->typeid; //所属类型	
                $addOrder->cardType = $card->cardType; //卡类型	
                $addOrder->createTime = date("Y-m-d H:i:s", time()); //创建时间	
                $addOrder->payTime = date("Y-m-d H:i:s", time()); //付款时间        
                $addOrder->url = ""; //相关地址
                $addOrder->state = 0; //状态         0：未付款 5、受理中 10：已付款  20：待充值  30：充值完成 100:撤消
                $addOrder->remark = ""; //备注
                $addOrder->save();
                $this->redirect('paying', 'pay', array('type' => Application_Model_PayBill::TYPE_ALI_CODE, 'id' => $addOrder->Id, 'count' => 1));
            } else {
                $this->view->message = "对不起,您选择的$money 元的卡已售完,请选择别的面值的卡号.";
            }
        }
    }

    /**
     * 代付款 
     */
    public function agentpayAction() {
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/replacerecharge.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $this->setTitle('代付款服务');

        if ($this->getRequest()->isPost()) {
            $pay = new Application_Model_AgentPay();
            $pay->MemberId = $this->currentUser()->Id;
            $pay->PayMoney = $this->_getParam('money');
            $pay->Code = $this->_getParam('code');
            $pay->Remark = $this->_getParam('remark');
            $pay->Url = $this->_getParam('payurl');
            $pay->Type = $this->_getParam('paytype');
            $pay->ProcessFee = Application_Model_Config::getProcessFee()->Value;
            $pay->dateCreated = date('Y-m-d H:i:s', time());
            $pay->save();
            $this->redirect('paying', 'pay', array('type' => Application_Model_PayBill::TYPE_AGENT_PAY, 'id' => $pay->Id, 'count' => 1));
        }
    }

    /**
     * 移动卡支付 
     */
    public function cardpayAction() {
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/cardpay.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $this->setTitle('购买移动卡');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $currentUser = $this->currentUser();

            $money = $request->getParam('money');

            $typeId = $request->getParam('type');


            //先判断卡是否
            $card = Application_Model_PayCodeCard::getFirstByType($typeId, 0);

            if ($card != null) {//库存足够
                //1获取卡信息
                $card->userID = $currentUser->Id;
                $card->state = 5;
                $card->userTime = date("Y-m-d H:i:s", time());
                $card->save();
                //2新增订单记录
                $addOrder = new Application_Model_PayCodeOrder();
                $addOrder->uid = $currentUser->Id; //用户ID	
                $addOrder->userName = $currentUser->nikename; //用户名	
                $addOrder->money = $money; //金额        
                $addOrder->cardid = $card->id; //授权卡序号	
                $addOrder->cardno = $card->cardNo; //授权卡号   	
                $addOrder->verifyCode = $card->cardPwd; //授权密码
                $addOrder->typeid = $card->typeid; //所属类型	
                $addOrder->cardType = $card->cardType; //卡类型	
                $addOrder->createTime = date("Y-m-d H:i:s", time()); //创建时间	
                $addOrder->payTime = date("Y-m-d H:i:s", time()); //付款时间        
                $addOrder->url = ""; //相关地址
                $addOrder->state = 0; //状态         0：未付款 5、受理中 10：已付款  20：待充值  30：充值完成 100:撤消
                $addOrder->remark = ""; //备注
                $addOrder->save();

                $this->redirect('paying', 'pay', array('type' => Application_Model_PayBill::TYPE_CARD, 'id' => $addOrder->Id, 'count' => 1));
            } else {
                $this->view->message = "对不起,您选择的$money 元的卡已售完,请选择别的面值的卡号,或者联系客服.";
            }
        }
    }

    /*
     * 移动卡列表
     */

    public function cardpaylistAction() {

        


        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/cardpay.css');

        $this->appendScript('/js/jquery.min.js');
        $this->appendScript('/js/jquery.validate.min.js');

        $this->setTitle('我的帐户 |  移动卡充值');
        $this->appendCss('/css/home/coupon.css');


        $start = $this->_getParam('start');
        if (!$start)
            $start = 0;

        $status = $this->_getParam('status');
//        if(!$status)
//            $status=-1;

        $stime = $this->_getParam('stime');
        if (!$stime)
            $stime = -3;

        $etime = $this->_getParam('etime');
        if (!$etime)
            $etime = 1;

        $this->pageSize = 10;

        $userid = $this->currentUser()->Id;
        $this->view->cardOrders = Application_Model_PayCodeOrder::getByFilter(NULL, $userid, date('Y-m-d', strtotime("$stime months")), date('Y-m-d', strtotime("$etime months")), $status, $this->pageSize, $start, 5);

        $this->view->cardOrder = $this->view->cardOrders['list'];
        $this->view->status = $status;
    }

    public function agentpaylistAction() {
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/alipaycode.css');

        $start = $this->_getParam('start');
        if (!$start)
            $start = 0;

        $this->view->list = Application_Model_AgentPay::getByFilter($this->currentUser()->Id, $start, $this->pageSize);
        $this->setTitle('我的代支付记录');

        $request = $this->getRequest();
        if ($request->isPost()) {
            $id = $request->getParam('id');    //ID
            $type = $request->getParam('type');   //操作类型，1为取消，2为删除

            if ($type == '2') {
                //删除代充值记录
                $agent = Application_Model_AgentPay::load($id);
                if ($agent) {
                    $agent->delete();
                }
            }
        }
    }

    public function alipaycodelistAction() {
        $this->appendCss('/css/Share.css');
        $this->appendCss('/css/home/alipaycode.css');


        $this->setTitle('我的帐户 |  移动卡充值');
        $this->appendCss('/css/home/coupon.css');


        $start = $this->_getParam('start');
        if (!$start)
            $start = 0;

        $status = $this->_getParam('status');
//        if(!$status)
//            $status=-1;

        $stime = $this->_getParam('stime');
        if (!$stime)
            $stime = -3;

        $etime = $this->_getParam('etime');
        if (!$etime)
            $etime = 1;

        $this->pageSize = 10;

        $userid = $this->currentUser()->Id;
        $this->view->cardOrders = Application_Model_PayCodeOrder::getByFilter(NULL, $userid, date('Y-m-d', strtotime("$stime months")), date('Y-m-d', strtotime("$etime months")), $status, $this->pageSize, $start, 10);

        $this->view->cardOrder = $this->view->cardOrders['list'];
        $this->view->status = $status;
    }

    public function forecastdetailAction() {
        $this->appendCss('/css/home/rmb.css');
        $id = $this->_getParam('id');
        $item = Application_Model_ingstore::load($id);
        $this->view->item = $item;
        $this->setTitle($item->Name . ' | 查看物流详情');
    }

    public function getexpressAction() {
        $id = $this->_getParam('id');
        $type = '';
        $no = '';
        $ship = NULL;
        if ($this->_getParam('type') == '2') {
            $bill = Application_Model_wayBillItem::load($id);
            $no = $bill->Logistics;
            $ship = $bill->getShipTypeBy();
            $type = $ship->Code;
        }else if($this->_getParam('type')=='3'){
            $order = Application_Model_Order::load($id);
            $no = $order->logisticsNo;
            $ship = $order->logisticsBy;
            $type = $ship->Code;
        } else {
            $instore = Application_Model_ingstore::load($id);

            $type = $instore->ShipTypeBy->Code;
            $no = $instore->ShipNo;
            $ship = $instore->ShipTypeBy;
        }

        $content = '';
        $isUrl = $ship->IsUrl;
        if ($isUrl) {
            $content = Uuch_Util::expressUrl($type, $no);
        } else {
            $content = Uuch_Util::express($type, $no);
        }

        $this->json(array('content' => $content, 'isUrl' => $isUrl));
    }

    public function selectstoreAction() {
        $id = $this->_getParam('itemid');
        $isSelected = $this->_getParam('selected');
        $item = Application_Model_StoreItem::load($id);
        if ($item->Userid != $this->currentUser()->Id) {
            $this->json(-1);
            return;
        }
        $item->IsSelected = $isSelected;
        $item->save();
        $selects = Application_Model_StoreItem::getMySelect($this->currentUser()->Id);
        $weight = Application_Model_StoreItem::getSumWeight($selects);
        $this->json(array('count' => count($selects), 'weight' => $weight));
    }

    public function newaddressAction() {
        $userid = $this->currentUser()->id;
        $newItem = new Application_Model_address();
        $newItem->state = $this->_getParam("state"); //所在国家
        //$newItem->province=$this->_getParam("province");
        //$newItem->city=$this->_getParam("City");
        $newItem->street = $this->_getParam("street");
        $newItem->comment = "";
        $newItem->postcode = $this->_getParam("postCode");
        $newItem->linkMan = $this->_getParam("linkMan");
        $newItem->mobile = $this->_getParam("mobile");
        //$newItem->phone=$this->_getParam("phone");
        $newItem->userId = $userid;
        $newItem->default = time(); //默认值
        $newItem->save();
        $this->view->newAddressId = $newItem->Id;
        
        $this->setcultfee($newItem->Id);
        $this->render('cultfee');
    }

    /**
     * 根据所选国家，计算运费 
     */
    public function cultfeeAction() {
        $addressId = $this->_getParam('address');
        $this->setcultfee($addressId);
    }

    private function setcultfee($addressId) {
        $userid = $this->currentUser()->Id;
        $items = Application_Model_StoreItem::getMySelect($userid);
        $this->view->volumeWeight = Application_Model_StoreItem::getSumVolumeWeight($items);
        $this->view->weight = Application_Model_StoreItem::getSumWeight($items);
        $this->view->bagWeight = Uuch_Util::getPackage($this->view->weight);
        $this->view->SumWeight = $this->view->bagWeight + $this->view->weight;
        
        $this->view->items = $items;

        $address = Application_Model_address::load($addressId);
        $this->view->city = $address->getCityBy();
        $this->view->prices = Application_Model_ExpressPrice::getPricesByCity($address->State);
        $this->_helper->layout->disableLayout();
    }

    public function waybillcreateAction() {
        $this->appendCss('/css/home/order.css');
        $this->setTitle('提交国际运单');
        $userid = $this->currentUser()->Id;
        $items = Application_Model_StoreItem::getMySelect($userid);
        if (count($items) == 0) {
            $this->redirect('mystore', 'member');
            return;
        }

        $this->view->volumeWeight = Application_Model_StoreItem::getSumVolumeWeight($items);
        $this->view->weight = Application_Model_StoreItem::getSumWeight($items);
        $this->view->itemCount = count($items);

        $this->view->bagWeight = Uuch_Util::getPackage($this->view->weight);
        $this->view->SumWeight = $this->view->bagWeight + $this->view->weight;
        $this->view->items = $items;

        $address = Application_Model_address::getByUserId($userid);
        $this->view->address = array_reverse(Uuch_Util::quickSort($address, 'Id'));
        if (count($address) == 0) {
            $this->view->default = new Application_Model_address(array('State' => 1));
            $this->view->hasAddress = false;
            $this->view->isEuro = FALSE;
        } else {
            $this->view->default = $address[count($address) - 1];
            $city = $this->view->default->getCityBy();
            $this->view->isEuro = ($city->AreaCode >=7 && $city->AreaCode <=10);
            $this->view->hasAddress = TRUE;
            
        }

        $this->view->prices = Application_Model_Express::getPricesByCity($this->view->default->State);

        $words = array();
        for ($i = 0; $i < 26; $i++) {
            $words [] = chr(65 + $i);
        }
        $cnShipFee = 0;
        foreach ($items as $item){
            $cnShipFee += $item->CnShipFee;
        }
        $this->view->words = $words;
        $this->view->cnShipFee = $cnShipFee;
        $this->view->coupons = Application_Model_Coupon::getByUser($userid, Application_Model_Coupon::STATUS_OK);
    }

    public function waybillsubmitAction() {
        $shipType = $this->_getParam('shipType');
        $ship = Application_Model_Express::load($shipType);
        $userid = $this->currentUser()->Id;
        $items = Application_Model_StoreItem::getMySelect($userid);
        
        if(count($items)==0){
            $this->redirect('mystore', 'member');
            return;
        }
        
        $cnShipFee = 0;
        foreach ($items as $item){
            $cnShipFee += $item->cnShipFee;
        }
        
        

        $productWeight = Application_Model_StoreItem::getSumWeight($items);
        $volumWeight = Application_Model_StoreItem::getSumVolumeWeight($items);

        $bagWeight = Uuch_Util::getPackage($productWeight);

        $weight = 0;
        $isVolume = FALSE;
        if ($ship->IsVolume && $volumWeight > $productWeight + $bagWeight) {
            $weight = $volumWeight;
            $isVolume = TRUE;
        } else {
            $weight = $productWeight + $bagWeight;
        }

        $addressId = $this->_getParam('addressId');
        $address = Application_Model_address::load($addressId);

        $ep = Application_Model_ExpressPrice::getPriceByExpressAndCity($ship->Id, $address->State);
        $shipFee = $ep->getMoneyByweight($weight);

        //$shipMoney = Application_Model_shipFeeConfig::getMoney($address->State, $ship->Id, $weight);

        $couponNo = $this->_getParam('couponno');
        $password = $this->_getParam('password');
        $discount = 0;
        $coupon = NULL;
        if ($couponNo != '0') {
            $coupon = Application_Model_Coupon::getByNo($couponNo);
            $couponResult = $coupon->Validate($userid, $shipFee, $password);
            if($couponResult->result){
                $discount = $couponResult->discount;
                $coupon->Status = Application_Model_Coupon::STATUS_USED;
            }
        }
        $serviceFee = 0; //暂时不收服务费
        
        $woodenFee = $this->_getParam('isWooden')?200:0;
        $compressFee = $this->_getParam('isCompress')?10:0;
        $premiumFee = 0;
        $premiumValue = 0;
        if($this->_getParam('isPremium')=='1'){
            $premiumValue = $this->_getParam('PremiumValue');
            if($premiumValue!=''){
                $premiumFee = $premiumValue * Application_Model_Config::getPremiumRate()->Value;
            }
        }
        
        $shipMoney = $shipFee - $discount + $ship->ReportFee + $serviceFee + $cnShipFee + $woodenFee + $compressFee + $premiumFee;
        if ($shipMoney < 0)
            $shipMoney = 0;

        $newItem = new Application_Model_wayBillItem();
        $wayCode = Uuch_Util::getWayCode();
        $newItem->billNo = $wayCode; //运单号
        $newItem->dateCreated = date('Y-m-d H:i:s'); //创建日期
        $newItem->status = Application_Model_wayBillItem::STATUS_WaitPay; //状态 0:等待付款 1：受理中(正在发货) 2:已经发货 100：已经完成 -1:取消 -2:海关退货；
        $newItem->userId = $userid; //用户ID
        $newItem->lastdate = $this->now();
        $newItem->IsVolume = $isVolume;
        $newItem->setAllWeight($weight, $bagWeight, $productWeight, $volumWeight);

        $newItem->shipType = $ship->Id; //运送方式
        $newItem->ExpressId = $ship->Id;
        $newItem->shipFeeconfig = $ep->Id; //
        $newItem->setAddress($address);

        $newItem->isNoLogo = $this->_getParam('isNoLogo') ? '1' : '0'; //是否去掉吊牌，Logo等
        $newItem->isNoSkin = $this->_getParam('isNoSkin') ? '1' : '0'; //是否要去掉不必要包装
        $newItem->isCompress = $this->_getParam('isCompress') ? '1' : '0'; //是否要压缩抽气
        $newItem->isWooden = $this->_getParam('isWooden')?'1':'0';

        
        $newItem->Remark =  $this->_getParam('remark');

        $newItem->setAllMoney($shipMoney, $shipFee, $ship->ReportFee, $discount, $serviceFee);
        $newItem->save();

        if ($couponNo != '0' && $discount>0) {
            $coupon->Relevance = $newItem->Id;
            $coupon->UseTime = $this->now();
            $coupon->save();
        }

        foreach ($items as $item) {
            $item->WayId = $newItem->Id;
            $item->State = Application_Model_StoreItem::STATUS_Sended;
            $item->IsSelected = FALSE;
            $item->save();
            $newItem->addItem($item->Id);
            $newItem->save();
        }
        
        //添加费用信息
        $newItem->addFee(Application_Model_FeeType::EstimateShipFee, $shipFee);
        $newItem->addFee(Application_Model_FeeType::CnShipFee, $cnShipFee);
        $newItem->addFee(Application_Model_FeeType::CouponFee, $discount * -1);
        $newItem->addFee(Application_Model_FeeType::ReportFee, $ship->ReportFee);
        $newItem->addFee(Application_Model_FeeType::OperationFee, $serviceFee);
        $newItem->addFee(Application_Model_FeeType::EstimateSum, $shipMoney);
        if($woodenFee>0){
            $newItem->addFee(Application_Model_FeeType::WoodenFee, $woodenFee);
        }
        
        if($compressFee>0){
            $newItem->addFee(Application_Model_FeeType::VacuumSeviceFee, $compressFee);
        }
        
        if($premiumFee){
            $newItem->addFee(Application_Model_FeeType::RatePremiumFee, $premiumFee);
            $newItem->addFee(Application_Model_FeeType::PremiumValue, $premiumValue);
        }
        
        $reportValue = $this->_getParam('reportValue');
        if($reportValue){
            $newItem->addFee(Application_Model_FeeType::ReprotValue, $reportValue);
        }
        
        //添加重量信息
        $newItem->addWeight(Application_Model_WeightType::ProductWeight, $productWeight);
        $newItem->addWeight(Application_Model_WeightType::BagWeight, $bagWeight);
        $newItem->addWeight(Application_Model_WeightType::EstimateWeight, $weight);
        $newItem->addWeight(Application_Model_WeightType::EstimateVolume, $volumWeight);
        
        $this->redirect('paying', 'pay', array('type' => Application_Model_PayBill::TYPE_WAYBILL, 'id' => $newItem->Id, 'count' => 1));
    }
    
    public function addressAction(){
        $this->setTitle('我的收货地址');
        $this->appendCss('/css/home/addressbook.css');
        $this->view->address = Application_Model_address::getbyuid($this->currentUser()->Id);
        $words = array();
        for ($i = 0; $i < 26; $i++) {
            $words [] = chr(65 + $i);
        }
        $this->view->city = Uuch_Util::getCurrentCity();
        $this->view->words = $words;
    }
    
    public function deladdressAction(){
        $id = $this->_getParam('id');
        $address = Application_Model_address::load($id);
        if($address->UserId == $this->currentUser()->Id){
            $address->delete();
        }
        $this->redirect('address', 'member');
    }

    public function saveaddressAction(){
        $userid = $this->currentUser()->id;
        $newItem = new Application_Model_address();
        $newItem->state = $this->_getParam("state"); //所在国家
        //$newItem->province=$this->_getParam("province");
        //$newItem->city=$this->_getParam("City");
        $newItem->street = $this->_getParam("street");
        $newItem->comment = "";
        $newItem->postcode = $this->_getParam("postcode");
        $newItem->linkMan = $this->_getParam("linkMan");
        $newItem->mobile = $this->_getParam("mobile");
        //$newItem->phone=$this->_getParam("phone");
        $newItem->userId = $userid;
        $newItem->default = time(); //默认值
        $newItem->save();
        $this->redirect('address', 'member');
    }
}
